package com.djx.provider.config.exception;

import com.djx.comm.MessageObject;
import com.djx.comm.enums.ResultEnum;
import com.djx.comm.exception.MyException;
import com.djx.comm.util.ResourcesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常处理
 * @author dingjunxiong
 */
@ControllerAdvice
public class ExceptionConfig {

    protected Logger logger = LoggerFactory.getLogger(ExceptionConfig.class);

    @ExceptionHandler
    @ResponseBody
    public Object defaultExceptionHandler(HttpServletRequest request, Exception ex) {
        // log记录异常
        logger.error("Handler execution resulted in exception", ex);

        MessageObject result = new MessageObject();
        if (ex instanceof MyException) {
            MyException exception = (MyException) ex;
            result.setCode(exception.getCode());
            result.setMessage(exception.getMessage());
        } else if (ex instanceof MaxUploadSizeExceededException) {
            MyException exception = (MyException) ex;
            result.setCode(exception.getCode());
            result.setMessage("导入文件总大小不可超过10M");
        } else if (ex instanceof IllegalArgumentException) {
            Exception arug = ex;
            result.setCode(ResultEnum.REDIS_EXCEPTION.getStatusCode());
            result.setMessage(arug.getMessage());
        } else if (ex instanceof HttpMessageNotReadableException) {
            result.setCode(ResultEnum.REDIS_EXCEPTION.getStatusCode());
            result.setMessage(ResourcesUtil.getMessage(ResultEnum.REQUEST_BODY_IS_MISSING.getKey()));
        } else {
            result.setCode(ResultEnum.REDIS_EXCEPTION.getStatusCode());
            result.setMessage(ResourcesUtil.getMessage(ResultEnum.REDIS_EXCEPTION.getKey()));
        }
        return result;
    }
}
